package md.sv.dbu.executor;

import md.sv.dbu.DBUExecutor;
import md.sv.dbu.config.jaxb.ConfigurationType;
import md.sv.dbu.config.jaxb.DbConnectionType;
import md.sv.dbu.config.jaxb.FormatDateTimeType;
import md.sv.dbu.config.jaxb.VariableType;
import md.sv.dbu.db.DBExecutor;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;

/**
 * @author MG
 */
public class ConfigParser implements DbuTypeExecutor {
    private static final Logger logger = LoggerFactory.getLogger(ConfigParser.class);

    private DBUExecutor dbuExecutor;

    @Override
    public void registerMainExecutor(DBUExecutor executor) {
        this.dbuExecutor = executor;
    }

    @Override
    public boolean isEligible(Object dbuElement) {
        return dbuElement instanceof ConfigurationType;
    }

    @Override
    public void execute(Object dbuElement) {
        ConfigurationType configurationType = (ConfigurationType) dbuElement;

        if (configurationType.getRootPath() != null) {
            dbuExecutor.setRootPath(configurationType.getRootPath());
        }

        if (configurationType.getLog() != null) {
            String logPath = FilenameUtils.concat(dbuExecutor.getRootPath(), configurationType.getLog().getPath());
            dbuExecutor.setGlobalLogging(configurationType.getLog().getLevel(), logPath);
        }

        initDateTimeFormats(configurationType);
        initVariables(configurationType);
        initDbConnections(configurationType);
    }

    private void initDateTimeFormats(ConfigurationType configurationType) {
        for (FormatDateTimeType formatDateTimeType : configurationType.getFormatDateTime())  {
            try {
                dbuExecutor.getDateTimeFormats().put(formatDateTimeType.getId(), new SimpleDateFormat(formatDateTimeType.getValue()));
            } catch (Exception e) {
                logger.error("formatDateTime with ID [{}] could not be initialized", formatDateTimeType.getId());
                logger.error("Error details: ", e);
            }
        }
    }

    private void initVariables(ConfigurationType configurationType) {
        for (VariableType variableType : configurationType.getVariable()) {
            String value = variableType.getVal();
            if (value == null) {
                value = variableType.getValue();
            }
            dbuExecutor.getVariables().put(variableType.getId(), value);
        }
    }

    private void initDbConnections(ConfigurationType configurationType) {
        for (DbConnectionType connectionType : configurationType.getDbConnection()) {
            dbuExecutor.getDbExecutors().putIfAbsent(connectionType.getId(), new DBExecutor(connectionType));
        }
    }

}
